(function(){
	var Collections = require('Collections'),
    ObjectUtils = require('ObjectUtils');

	var Map     = Collections.Map;
	var iterate = Collections.iterate;
	var merge   = ObjectUtils.merge;
		
	namespace('org.jsmud');
	
	org.jsmud.AliasService = function(db){
		this.db = db;
	};
	org.jsmud.AliasService.prototype = {
		findAll : function(onLoad){
			this.findByExample({}, onLoad);
		},
		findByExample : function(example, onLoad){
			var db = this.db;
			var onSuccess = function(obj){
				if( onLoad ) onLoad(obj.length ? obj : null);
			};
			var onError = function(err){
				if( onLoad ) onLoad({error:err});
			};
			db.find({example:example}, onSuccess, onError);
		},
		save : function(room, onSuccess, onError){
			var db = this.db;
			db.save(room, onSuccess, onError)
		},
		commands : {
			addAlias : {
				onExecute : function(name, commandName){
					var aliasService = this.owner;
					this.owner.findByExample({name:name}, function(alias){
						if(alias){
							alias[0].commandName = commandName;
							aliasService.save(alias[0]);
						}else{
							aliasService.save({name:name, commandName:commandName})
						}
					});
					
				},
				onAutoComplete : function(){
					
				}
			},
			list : {
				onExecute : function(){
					var onDone = this.onResponse;
					this.owner.findByExample({}, function(aliases){
						console.log(aliases);
						aliases.toHTML = function(){
							var html = '';
							iterate( aliases, function(alias){
								html += '<span>' + alias.name + '=' + alias.commandName +'</span><br/>';
							});
							return html;
						}
						onDone( aliases );
					});
				}
			}
		},
		getCommands : function(onResponse){
			var results = {};
			Map.putAll(results, this.commands, merge({owner:this}).mapEntry );
			this.findAll(function(aliases){
				iterate(aliases, function(alias){
					results[alias.name] = {
						onExecute : function(){
							var onResponse2 = this.onResponse;
							this.commandService.doExecute(alias.commandName, arguments, onResponse2);
						}
						,onAutoComplete : function(value){
							var onResponse2 = this.onResponse;
							this.commandService.get(alias.commandName, function(command){
								command.autoComplete(value, onResponse2);
							});
						}
					};
				});
				onResponse(results);
			});
		}
	};
})();